package com.newway.config;

import com.newway.wechat.inteceptor.WechatUserInfoInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
@EnableAsync
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    WechatUserInfoInterceptor wechatUserInfoInterceptor;
    @Autowired
    Environment environment;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(wechatUserInfoInterceptor)
                .addPathPatterns("/wechat/**")
                .excludePathPatterns("/wechat/login","/wechat/register","/wechat/ai/**","/wechat/download/*","/wechat/uploads/**","/wechat/cook/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 所有接口
                .allowedOriginPatterns("*") // 允许所有来源（生产环境建议指定具体域名）
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的 HTTP 方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(true) // 允许携带 Cookie
                .maxAge(3600); // 预检请求缓存时间（秒）
    }


    /**
     * 解决日志提醒
     * @param configurer
     */

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setTaskExecutor(asyncExecutor());
        configurer.setDefaultTimeout(60000); // 设置默认超时时间（毫秒）
    }

    @Bean(name = "asyncExecutor")
    public ThreadPoolTaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10); // 核心线程数
        executor.setMaxPoolSize(50); // 最大线程数
        executor.setQueueCapacity(100); // 任务队列容量
        executor.setThreadNamePrefix("Async-Executor-"); // 线程名称前缀
        executor.initialize();
        return executor;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadPath = environment.getProperty("img.uploadPath");
        String mappingPath = environment.getProperty("img.mappingPath");
        //映射上传目录为静态资源
        registry.addResourceHandler(mappingPath+"**")
                .addResourceLocations("file:"+uploadPath)
                .setCachePeriod(3600);
    }
}
